package cn.czg.cms.netty;

import cn.czg.cms.entity.dto.MessageDTO;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

public class WebSocketHandler extends SimpleChannelInboundHandler<MessageDTO> {

    private final NettyChannelManager manager;

    public WebSocketHandler(NettyChannelManager manager) {
        this.manager = manager;
    }


    @Override
    public void channelRead0(ChannelHandlerContext ctx, MessageDTO msg) {
        if ("heartbeat".equals(msg.getType())) {
            Long fromId = msg.getFromId();
            System.out.println("💓 心跳包 fromId=" + (fromId != null ? fromId : "未知"));
            ctx.writeAndFlush(new TextWebSocketFrame("{\"type\":\"pong\"}"));
            return;
        }
        // 业务处理
        System.out.println("📨 收到业务消息: " + msg.getContent());
        // ...转发、响应等逻辑
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent idleEvent && idleEvent.state() == IdleState.READER_IDLE) {
            System.out.println("💤 客户端 30 秒未发送数据，关闭连接: " + ctx.channel().remoteAddress());
            ctx.close();
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        Long userId = manager.getUserId(ctx.channel());
        if (userId != null) {
            manager.remove(userId);
            System.out.println("❌ 用户断开: userId=" + userId);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.err.println("异常：" + cause.getMessage());
        ctx.close();
    }

    private String parseUserIdFromUri(String uriStr) {
        try {
            URI uri = new URI(uriStr);
            String query = uri.getQuery();
            if (query == null) return null;
            for (String pair : query.split("&")) {
                String[] kv = pair.split("=");
                if (kv.length == 2 && kv[0].equals("userId")) {
                    return URLDecoder.decode(kv[1], StandardCharsets.UTF_8);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
